#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证文件调试脚本
用于检查和修复登录认证相关问题
"""
import os
import json
from pathlib import Path

def debug_auth_file():
    """调试认证文件"""
    print("🔍 开始调试认证文件...")
    
    # 获取认证文件路径
    root_dir = Path(__file__).resolve().parent
    auth_dir = root_dir / 'auth'
    storage_file = auth_dir / 'storage_state.json'
    
    print(f"📁 项目根目录: {root_dir}")
    print(f"📁 认证目录: {auth_dir}")
    print(f"📄 认证文件: {storage_file}")
    
    # 检查目录是否存在
    if not auth_dir.exists():
        print("❌ auth 目录不存在，正在创建...")
        auth_dir.mkdir(parents=True, exist_ok=True)
        print("✅ auth 目录已创建")
    else:
        print("✅ auth 目录存在")
    
    # 检查认证文件
    if not storage_file.exists():
        print("❌ 认证文件不存在")
        return False
    
    print("✅ 认证文件存在")
    
    # 检查文件大小
    file_size = storage_file.stat().st_size
    print(f"📊 文件大小: {file_size} bytes")
    
    if file_size == 0:
        print("❌ 认证文件为空")
        return False
    
    # 检查文件内容
    try:
        with open(storage_file, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"📄 文件内容长度: {len(content)} 字符")
            
        # 验证JSON格式
        with open(storage_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            print("✅ JSON 格式有效")
            print(f"📊 JSON 键数量: {len(data)}")
            
            # 检查关键字段
            if 'cookies' in data:
                print(f"🍪 Cookies 数量: {len(data['cookies'])}")
            if 'origins' in data:
                print(f"🌐 Origins 数量: {len(data['origins'])}")
                
        return True
        
    except json.JSONDecodeError as e:
        print(f"❌ JSON 格式错误: {e}")
        return False
    except Exception as e:
        print(f"❌ 读取文件错误: {e}")
        return False

def clean_auth_file():
    """清理认证文件"""
    print("🧹 清理认证文件...")
    
    root_dir = Path(__file__).resolve().parent
    auth_dir = root_dir / 'auth'
    storage_file = auth_dir / 'storage_state.json'
    
    if storage_file.exists():
        try:
            storage_file.unlink()
            print("✅ 认证文件已删除")
        except Exception as e:
            print(f"❌ 删除失败: {e}")
    else:
        print("ℹ️ 认证文件不存在，无需删除")

def create_empty_auth_file():
    """创建空的认证文件"""
    print("📝 创建空认证文件...")
    
    root_dir = Path(__file__).resolve().parent
    auth_dir = root_dir / 'auth'
    storage_file = auth_dir / 'storage_state.json'
    
    # 确保目录存在
    auth_dir.mkdir(parents=True, exist_ok=True)
    
    # 创建空的有效JSON文件
    empty_auth = {
        "cookies": [],
        "origins": []
    }
    
    try:
        with open(storage_file, 'w', encoding='utf-8') as f:
            json.dump(empty_auth, f, indent=2)
        print("✅ 空认证文件已创建")
    except Exception as e:
        print(f"❌ 创建失败: {e}")

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1:
        action = sys.argv[1]
        if action == "clean":
            clean_auth_file()
        elif action == "create":
            create_empty_auth_file()
        elif action == "debug":
            debug_auth_file()
        else:
            print("用法: python debug_auth.py [debug|clean|create]")
    else:
        # 默认执行调试
        is_valid = debug_auth_file()
        if not is_valid:
            print("\n🔧 建议操作:")
            print("1. 清理认证文件: python debug_auth.py clean")
            print("2. 重新运行测试让系统自动登录")
